from fastapi import APIRouter, HTTPException, Depends, File, UploadFile, Query
from sqlalchemy.orm import Session
from pydantic import BaseModel
from typing import List, Optional
import datetime
import random
import os
from pathlib import Path

from commons.database import Database
from DAL.product import Product
from DAL.category import Category
from DAL.user import User

# 创建API路由
router = APIRouter(prefix='/api', tags=['product'])

# Pydantic模型定义
class ProductCreate(BaseModel):
    name: str
    category_id: int
    price: float
    description: Optional[str] = None
    bank_account_name: Optional[str] = None
    bank_account_number: Optional[str] = None
    payment_instructions: Optional[str] = None

class ProductUpdate(BaseModel):
    name: Optional[str] = None
    category_id: Optional[int] = None
    price: Optional[float] = None
    description: Optional[str] = None
    is_active: Optional[bool] = None
    bank_account_name: Optional[str] = None
    bank_account_number: Optional[str] = None
    payment_instructions: Optional[str] = None

class ProductResponse(BaseModel):
    id: int
    seller_id: int
    name: str
    cover_image: str
    category_id: int
    price: float
    description: Optional[str] = None
    is_active: bool
    created_at: datetime.datetime
    updated_at: datetime.datetime
    bank_account_name: Optional[str] = None
    bank_account_number: Optional[str] = None
    payment_instructions: Optional[str] = None
    detail_images: Optional[List[str]] = None

    class Config:
        from_attributes = True

# 辅助函数：获取数据库会话
def get_db():
    db = next(Database.get_db())
    try:
        yield db
    finally:
        db.close()

# 辅助函数：验证卖家权限
def verify_seller(db: Session, user_id: int):
    user = db.query(User).filter(User.id == user_id).first()
    if not user or not user.is_approved:
        raise HTTPException(status_code=403, detail="没有卖家权限")
    return user

# 辅助函数：生成唯一文件名
def generate_filename(ext: str) -> str:
    date_part = datetime.datetime.now().strftime("%Y%m%d")
    time_part = datetime.datetime.now().strftime("%H%M%S") + f"{random.randint(0, 99):02d}"
    return f"{date_part}_{time_part}{ext.lower()}"

# 产品图片上传接口
@router.post("/products/upload-image", response_model=dict)
async def upload_product_image(file: UploadFile = File(...)):
    """
    上传产品图片
    返回图片路径
    """
    # 验证文件类型
    allowed_extensions = {'.jpg', '.jpeg', '.png', '.gif'}
    ext = os.path.splitext(file.filename)[1].lower()
    if ext not in allowed_extensions:
        raise HTTPException(status_code=400, detail="不支持的图片格式")

    # 生成文件名和路径
    filename = generate_filename(ext)
    upload_dir = Path("uploads/products")
    upload_dir.mkdir(parents=True, exist_ok=True)
    file_path = str(upload_dir / filename).replace('\\', '/')

    # 保存文件
    with open(file_path, "wb+") as file_object:
        file_object.write(await file.read())

    return {"message": "图片上传成功", "file_path": file_path}

# 创建产品接口
@router.post("/products", response_model=ProductResponse)
def create_product(
    product: ProductCreate,
    seller_id: int,
    cover_image: str,
    detail_images: Optional[List[str]] = None,
    db: Session = Depends(get_db)
):
    """
    创建新产品
    需要卖家权限
    """
    # 验证卖家权限
    verify_seller(db, seller_id)

    # 验证分类是否存在
    category = db.query(Category).filter(Category.id == product.category_id).first()
    if not category:
        raise HTTPException(status_code=404, detail="分类不存在")

    # 创建产品
    db_product = Product(
        seller_id=seller_id,
        name=product.name,
        cover_image=cover_image,
        category_id=product.category_id,
        price=product.price,
        description=product.description,
        bank_account_name=product.bank_account_name,
        bank_account_number=product.bank_account_number,
        payment_instructions=product.payment_instructions,
        detail_images=detail_images or []
    )

    db.add(db_product)
    db.commit()
    db.refresh(db_product)
    return db_product

# 获取产品列表接口
@router.get("/products", response_model=List[ProductResponse])
def get_products(
    skip: int = 0,
    limit: int = 100,
    category_id: Optional[int] = None,
    seller_id: Optional[int] = None,
    is_active: Optional[bool] = True,
    db: Session = Depends(get_db)
):
    """
    获取产品列表
    可按分类、卖家和状态筛选
    """
    query = db.query(Product)
    if category_id:
        query = query.filter(Product.category_id == category_id)
    if seller_id:
        query = query.filter(Product.seller_id == seller_id)
    if is_active is not None:
        query = query.filter(Product.is_active == is_active)
    return query.offset(skip).limit(limit).all()

# 获取单个产品接口
@router.get("/products/{product_id}", response_model=ProductResponse)
def get_product(product_id: int, db: Session = Depends(get_db)):
    """
    获取单个产品详情
    """
    product = db.query(Product).filter(Product.id == product_id).first()
    if not product:
        raise HTTPException(status_code=404, detail="产品不存在")
    return product

# 更新产品接口
@router.put("/products/{product_id}", response_model=ProductResponse)
def update_product(
    product_id: int,
    product_update: ProductUpdate,
    seller_id: int,
    db: Session = Depends(get_db)
):
    """
    更新产品信息
    需要卖家权限且只能更新自己的产品
    """
    # 验证卖家权限
    verify_seller(db, seller_id)

    # 获取产品并验证所有权
    product = db.query(Product).filter(Product.id == product_id).first()
    if not product:
        raise HTTPException(status_code=404, detail="产品不存在")
    if product.seller_id != seller_id:
        raise HTTPException(status_code=403, detail="没有权限更新此产品")

    # 更新产品信息
    update_data = product_update.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(product, key, value)

    db.commit()
    db.refresh(product)
    return product

# 删除产品接口
@router.delete("/products/{product_id}", response_model=dict)
def delete_product(product_id: int, seller_id: int, db: Session = Depends(get_db)):
    """
    删除产品
    需要卖家权限且只能删除自己的产品
    """
    # 验证卖家权限
    verify_seller(db, seller_id)

    # 获取产品并验证所有权
    product = db.query(Product).filter(Product.id == product_id).first()
    if not product:
        raise HTTPException(status_code=404, detail="产品不存在")
    if product.seller_id != seller_id:
        raise HTTPException(status_code=403, detail="没有权限删除此产品")

    # 删除产品
    db.delete(product)
    db.commit()
    return {"message": "产品已删除"}

# 更新产品图片接口
@router.put("/products/{product_id}/images", response_model=dict)
def update_product_images(
    product_id: int,
    seller_id: int,
    cover_image: Optional[str] = None,
    detail_images: Optional[List[str]] = None,
    db: Session = Depends(get_db)
):
    """
    更新产品图片
    可更新封面图和详情图列表
    """
    # 验证卖家权限
    verify_seller(db, seller_id)

    # 获取产品并验证所有权
    product = db.query(Product).filter(Product.id == product_id).first()
    if not product:
        raise HTTPException(status_code=404, detail="产品不存在")
    if product.seller_id != seller_id:
        raise HTTPException(status_code=403, detail="没有权限更新此产品")

    # 更新图片
    if cover_image:
        product.cover_image = cover_image
    if detail_images is not None:
        product.detail_images = detail_images

    db.commit()
    return {"message": "产品图片已更新"}